{/* Copyright 2020 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License. */}

import {Layout} from '@react-spectrum/docs';
export default Layout;

import docs from 'docs:@react-aria/button';
import statelyDocs from 'docs:@react-stately/toggle';
import {HeaderInfo, FunctionAPI, TypeContext, InterfaceType, TypeLink, PageDescription} from '@react-spectrum/docs';
import {Keyboard} from '@react-spectrum/text';
import packageData from '@react-aria/button/package.json';

---
category: Buttons
keywords: [button, toggle button, aria, form]
---

# useToggleButton

<PageDescription>{docs.exports.useToggleButton.description}</PageDescription>

<HeaderInfo
  packageData={packageData}
  componentNames={['useToggleButton']}
  sourceData={[
    {type: 'W3C', url: 'https://www.w3.org/WAI/ARIA/apg/patterns/button/'}
  ]} />

## API

<FunctionAPI function={docs.exports.useToggleButton} links={docs.links} />

## Features

Toggle buttons are similar to action buttons, but support an additional selection state
that is toggled when a user presses the button. There is no built-in HTML element that
represents a toggle button, so React Aria implements it using ARIA attributes.

* Native HTML `<button>`, `<a>`, and custom element type support
* Exposed as a toggle button via ARIA
* Mouse and touch event handling, and press state management
* Keyboard focus management and cross browser normalization
* Keyboard event support for <Keyboard>Space</Keyboard> and <Keyboard>Enter</Keyboard> keys

## Anatomy

Toggle buttons consist of a clickable area usually containing a textual label or an icon
that users can click to toggle a selection state. In addition, keyboard users may toggle
the state using the <Keyboard>Space</Keyboard> or <Keyboard>Enter</Keyboard> keys.

`useToggleButton` returns props to be spread onto the button element, along with a boolean indicating
whether the user is currently pressing the button:

<TypeContext.Provider value={docs.links}>
  <InterfaceType properties={docs.links[docs.exports.useToggleButton.return.base.id].properties} />
</TypeContext.Provider>

Selection state is managed by the <TypeLink links={statelyDocs.links} type={statelyDocs.exports.useToggleState} />
hook in `@react-stately/toggle`. The state object should be passed as an option to `useToggleButton`.

If a visual label is not provided (e.g. an icon only button), then an `aria-label` or
`aria-labelledby` prop must be passed to identify the button to assistive technology.

## Example

By default, `useToggleButton` assumes that you are using it with a native `<button>` element. You can use a custom
element type by passing the `elementType` prop to `useToggleButton`. See the [useButton](../Button/useButton.html#custom-element-type)
docs for an example of this.

The following example shows how to use the `useToggleButton` and `useToggleState` hooks to build a toggle button.
The toggle state is used to switch between a green and blue background when unselected and selected respectively.
In addition, the `isPressed` state is used to adjust the background to be darker when the user presses down on the button.

```tsx example export=true
import {useRef} from 'react';
import {useToggleButton} from '@react-aria/button';
import {useToggleState} from '@react-stately/toggle';

function ToggleButton(props) {
  let ref = useRef<HTMLButtonElement | null>(null);
  let state = useToggleState(props);
  let {buttonProps, isPressed} = useToggleButton(props, state, ref);

  return (
    <button
      {...buttonProps}
      style={{
        background: isPressed
          ? state.isSelected ? 'darkgreen' : 'gray'
          : state.isSelected ? 'green' : 'lightgray',
        color: state.isSelected ? 'white' : 'black',
        padding: 10,
        fontSize: 16,
        userSelect: 'none',
        WebkitUserSelect: 'none',
        border: 'none'
      }}
      ref={ref}>
      {props.children}
    </button>
  );
}

<ToggleButton>Pin</ToggleButton>
```

## Usage

The following examples show how to use the `ToggleButton` component created in the above example.

### Controlled selection state

A default selection state for a toggle button can be set using the `defaultSelected` prop, or controlled with the `isSelected` prop. The `onChange` event is fired when the user presses the button, toggling the boolean. See React's documentation on
[uncontrolled components](https://reactjs.org/docs/uncontrolled-components.html) for more info.

```tsx example
function Example() {
  let [isSelected, setSelected] = React.useState(false);

  return (
    <ToggleButton
      isSelected={isSelected}
      onChange={setSelected}
      aria-label="Star">
      ★
    </ToggleButton>
  );
}
```

### Disabled

A `ToggleButton` can be disabled using the `isDisabled` prop.

```tsx example
<ToggleButton isDisabled>Pin</ToggleButton>
```
